<template>
  <div class="page-container">

    <h2 class="page-title">设备使用分析总览</h2>

    <el-row :gutter="20">

      <el-col :span="12">
        <el-card class="card-shadow">
          <div class="card-header">各部门设备使用数量</div>
          <div ref="deptChart" class="chart-box"></div>
        </el-card>
      </el-col>

       <el-col :span="12">
        <el-card class="card-shadow">
          <div class="card-header">设备类别使用统计</div>
          <div ref="categoryChart" class="chart-box"></div>
        </el-card>
      </el-col>

       <el-col :span="12" class="mt-20">
          <el-card class="card-shadow warning-card">
            <div class="card-header warning-header">
              <div class="flex-center">
                <el-icon :size="20" class="mr-5"><WarningFilled /></el-icon>
                <span>今日超时使用预警</span>
              </div>
              <div class="flex-center">
                <span class="mr-5 text-secondary">阈值(小时)：</span>
                <el-input-number
                  v-model="threshold"
                  :min="0"
                  :step="0.5"
                  size="small"
                  controls-position="right"
                  style="width: 100px;"
                />
              </div>
            </div>
            
            <div class="warning-table-wrapper">
              <el-table
                :data="warningList"
                size="small"
                border
                height="100%"
                :row-class-name="warningRowClassName"
              >
                <el-table-column prop="deviceName" label="设备名称" />
                <el-table-column prop="deviceModel" label="设备型号" />
                <el-table-column prop="todayUsageDuration" label="今日使用时长（小时）" align="center" width="180"/>

                <template #empty>
                  <div class="custom-empty-state">
                    <el-icon :size="40" color="#67C23A"><SuccessFilled /></el-icon>
                    <p>今日无超时设备</p>
                  </div>
                </template>
              </el-table>
            </div>
          </el-card>
       </el-col>


        <el-col :span="12" class="mt-20">
          <el-card class="card-shadow">
            <div class="card-header">今日各类别使用总时长</div>
            <div ref="todayCategoryChart" class="chart-box"></div>
          </el-card>
        </el-col>
      </el-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import { WarningFilled, SuccessFilled } from '@element-plus/icons-vue'
import { deviceUsageApi } from '@/pages/deviceUse/components/DeviceUseAnalysis'
import type { DeviceUsageAnalysis } from '@/pages/deviceUse/components/DeviceUseAnalysis'

const deptChart = ref<HTMLDivElement>()
const categoryChart = ref<HTMLDivElement>()
const todayCategoryChart = ref<HTMLDivElement>()

const threshold = ref(2)
const warningList = ref<DeviceUsageAnalysis[]>([])
const warningLoading = ref(false)

// 部门使用数量 - 水平条形图
const loadDepartmentStats = () => {
  deviceUsageApi.getDepartmentUsageCount().then((data: DeviceUsageAnalysis[]) => {
    nextTick(() => {
      const chart = echarts.init(deptChart.value!)
      chart.setOption({
        tooltip: { trigger: 'axis' },
        grid: { left: '15%', right: '5%' },
        xAxis: { type: 'value' },
        yAxis: { type: 'category', data: data.map(d => d.department) },
        series: [{
          data: data.map(d => d.deviceCount),
          type: 'bar',
          color: '#4DB3FF',
          label: { show: true, position: 'right' }
        }]
      })
      window.addEventListener('resize', () => chart.resize())
    })
  })
}

// 类别统计 - 堆叠柱状图 + 折线
const loadCategoryStats = () => {
  deviceUsageApi.getCategoryStats().then((data: DeviceUsageAnalysis[]) => {
    nextTick(() => {
      const chart = echarts.init(categoryChart.value!)
      chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['总时长（小时）', '使用次数'] },
        grid: { left: '5%', right: '5%', bottom: '10%' },
        xAxis: { type: 'category', data: data.map(d => d.category) },
        yAxis: { type: 'value' },
        series: [
          { name: '总时长（小时）', type: 'bar', stack: '总量', data: data.map(d => d.totalDuration), color: '#67C23A' },
          { name: '使用次数', type: 'line', yAxisIndex: 0, data: data.map(d => d.totalTimes), color: '#E6A23C' }
        ]
      })
      window.addEventListener('resize', () => chart.resize())
    })
  })
}

// 超时预警
const loadTodayWarning = () => {
  warningLoading.value = true
  deviceUsageApi.getTodayHighUsageWarningList(threshold.value).then(data => {
    warningList.value = data
  }).catch(error => {
    console.error("加载预警列表失败:", error);
    warningList.value = [];
  }).finally(() => {
    warningLoading.value = false
  })
}

let debounceTimer: number | null = null
watch(threshold, () => {
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  debounceTimer = window.setTimeout(() => {
    loadTodayWarning()
  }, 500)
})

// 根据使用时长动态添加行样式
const warningRowClassName = ({ row }: { row: DeviceUsageAnalysis }) => {
  if (row.todayUsageDuration === null || row.todayUsageDuration === undefined) {
    return ''; // 如果没有时长数据，不加样式
  }
  const duration = row.todayUsageDuration;
  if (duration >= threshold.value * 2) { // 超过阈值两倍，严重警告
    return 'warning-row-critical';
  } else if (duration >= threshold.value * 1.5) { // 超过阈值1.5倍，中度警告
    return 'warning-row-moderate';
  } else if (duration >= threshold.value) { // 达到阈值，轻度警告
    return 'warning-row-minor';
  }
  return ''; // 未达到阈值，不加样式
}

// 今日类别总时长 - 环形饼图
const loadTodayCategoryUsage = () => {
  deviceUsageApi.getTodayCategoryUsage().then((data: DeviceUsageAnalysis[]) => {
    nextTick(() => {
      const chart = echarts.init(todayCategoryChart.value!)
      chart.setOption({
        tooltip: { trigger: 'item', formatter: '{b}: {c} 小时 ({d}%)' },
        legend: { orient: 'vertical', left: 'left' },
        series: [{
          name: '使用总时长',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: { show: false, position: 'center' },
          emphasis: { label: { show: true, fontSize: 14, fontWeight: 'bold' } },
          labelLine: { show: false },
          data: data.map(d => ({
            name: d.category,
            value: d.todayUsageDuration
          }))
        }]
      })
      window.addEventListener('resize', () => chart.resize())
    })
  })
}

onMounted(() => {
  loadDepartmentStats()
  loadCategoryStats()
  loadTodayWarning()
  loadTodayCategoryUsage()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  padding: 20px;
  background-color: #f5f7fa;

  .page-title {
    font-size: 22px;
    margin-bottom: 25px;
    font-weight: bold;
    color: #303133;
  }
}

.card-shadow {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column; // 让卡片内部内容垂直布局
  height: 100%; // 确保卡片本身占满父 el-col 的高度
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF; // 默认标题颜色
  padding: 10px 15px; // 统一内边距
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0; // 防止头部收缩
}

.chart-box {
  flex: 1; // 让图表盒子填充剩余空间
  min-height: 350px; // 保持图表最小高度，预警表格也会参照这个高度
  background: #fff;
  padding: 10px;
  border-radius: 6px;
  width: 100%;
  display: flex; // 确保内部内容（如echarts实例）可以填充
  justify-content: center;
  align-items: center;
}

.mt-20 {
  margin-top: 20px;
}

.flex-center {
  display: flex;
  align-items: center;
}
.mr-5 {
  margin-right: 5px;
}
.ml-5 {
  margin-left: 5px;
}
.text-secondary {
  font-size: 14px;
  color: #606266;
  font-weight: normal;
}

.full-height {
  height: 100%;
  // card-shadow 已经设置了 flex 布局，这里只需确保高度
}

// 新增表格包裹层，确保其能像 chart-box 一样弹性填充空间
.warning-table-wrapper {
  flex: 1; /* 让表格容器填充剩余空间 */
  overflow: auto; /* 当表格内容超出时显示滚动条 */
  min-height: 0; /* 关键：允许 flex item 在列布局中收缩，防止内容溢出 */
  background-color: #fff; // 确保表格区域背景色一致
  padding: 10px; // 表格周围的内边距
  display: flex; // 让内部的 el-table 也能更好地填充
  flex-direction: column; // 让表格作为 flex 子项
}

// 针对 el-table 内部元素进行样式穿透
:deep(.el-table) {
  height: 100%; // 让表格本身填充其父容器 `warning-table-wrapper` 的高度
  // 如果需要表头和内容区域有不同的背景，可以在这里设置
  .el-table__header-wrapper {
    background-color: #f7f9fc; // 轻微的表头背景色
  }
}

// 美化后的表格行颜色
:deep(.el-table .warning-row-minor) {
  background-color: #fffbe6 !important; // 淡黄色，轻度警告
}
:deep(.el-table .warning-row-moderate) {
  background-color: #fffae6 !important; // 稍深一点的黄色，中度警告
}
:deep(.el-table .warning-row-critical) {
  background-color: #fff5e6 !important; // 更深的橙黄色，严重警告
}

.custom-empty-state {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  min-height: 120px; /* 用固定高度避免父容器不稳定 */
  padding: 20px;
  color: #909399;
  background: transparent;
  cursor: default; /* 鼠标正常，避免误导 */

  .el-icon {
    font-size: 40px;
    color: #67C23A;
  }

  p {
    margin-top: 10px;
    font-size: 14px;
    color: #606266;
  }
}


// 警告卡片的特殊样式
.warning-card {
  border: 1px solid #E6A23C;
  // min-height 在 card-shadow 中处理，这里不再单独设置
  .warning-header {
    background-color: #fdf6ec;
    color: #E6A23C; // 警告标题颜色
    margin-bottom: 0; // 移除默认的 margin-bottom
  }
}
</style>